package com.wardrobe.configuration;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;

@Configuration
@PropertySource(value= "classpath:datasource.properties")
public class DataSourceConfiguration {

	@Value("${hikaricp.connectionTestQuery}")
	private String connectionTestQuery;

	@Bean("masterDataSourceProperties")
	@Primary
	@ConfigurationProperties(prefix="master.datasource")
	public DataSourceProperties masterDataSourceProperties(){
		return new DataSourceProperties();
	}

	@Bean("masterDataSource")
	@Primary
	@ConfigurationProperties(prefix="master.datasource")
	public DataSource  masterDataSource(@Qualifier("masterDataSourceProperties") DataSourceProperties masterDataSourceProperties){
		 HikariDataSource ds = (HikariDataSource)masterDataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
		ds.setConnectionTestQuery(connectionTestQuery);
		 return ds;
	}
	
	
	@Bean("slaveDataSourceProperties")
	@ConfigurationProperties(prefix="slave.datasource")
	public DataSourceProperties slaveDataSourceProperties(){
		return new DataSourceProperties();
	}

	@Bean("slaveDataSource")
	@ConfigurationProperties(prefix="slave.datasource")
	public DataSource slaveDataSource(@Qualifier("slaveDataSourceProperties") DataSourceProperties slaveDataSourceProperties  ){
		HikariDataSource ds = (HikariDataSource)slaveDataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
		ds.setConnectionTestQuery(connectionTestQuery);
		return ds;
	}
}
